<?php
/**
* 核心分发器
*/
//为测试暂时注释
defined('WALL_CODE') or exit('No permission resources.'); 
class Dispatcher{
	public static $_path = null;
	public static $_config = null;//配置数组

	function __construct(){
		//实例化核心，获取用户URI
		//为测试暂时注释
		self::$_path = parse_url($_SERVER['REQUEST_URI']);
	}

	public function run($config){
		//加载配置文件
		self::$_config = $config['system'];
		$this->init();
		$this->dispatch();

	}
	//加载配置文件
	final protected function loadConfig(){
		return self::$_config;
	}
	//框架运行初始化
	final protected function init(){
		require ROOT_PATH.'/core/Sql.class.php';
		require ROOT_PATH.'/core/smarty/Smarty.class.php';
		require ROOT_PATH.'/core/Model.class.php';
		require ROOT_PATH.'/core/Controller.class.php';
		require ROOT_PATH.'/core/View.class.php';
	}
	//请求分发
	final protected function dispatch(){
		//分析URI，得到相应的控制器和方法
		if (self::$_config['setting']['url_model']) {
			$tmp = $this->pathinfo_handler(self::$_path['path']);
		}else {
			$tmp = $this->get_handler(self::$_path['query']);
		}
		//获取相应的控制器、方法名称
		//url格式    域名/index.php?m=模型&c=控制器&a=方法
		$model = (empty($tmp['m'])) ? "index" : $tmp['m'];
		$controller = (empty($tmp['c'])) ? "index" : $tmp['c'] ;
		$action = (empty($tmp['a'])) ? "index" : $tmp['a'] ;

		//构造控制器路径
		$path_controller = ROOT_PATH.'/'.CONTROLLER_DIR.'/';
		$path_model = ROOT_PATH.'/'.MODEL_DIR.'/';
		
		//判断模型文件是否存在，并加载
		$path_model.= $model.'Model.php';
		if (file_exists($path_model)) {
			require $path_model;
		}
		
		//判断对应控制器文件是否存在并加载
		$path_controller.= $controller.'Controller.php';
		$file = file_exists($path_controller);
		if ($controller!="") {
			if ($file) {
				require $path_controller;
				$controller.='Controller';
				$C = new $controller;
				//判断方法是否存在，并执行对应方法
				if (method_exists($C, $action)) {
					$C->$action();
				}else{
					die("action not exists!");
				}
			}else{
				die("controller not exists!");
			}
		}
	}
	
	//实现URL的pathinfo格式
	//url格式    域名/模型/控制器/方法/参数名1/参数值1/参数名2/参数值2
	protected function pathinfo_handler($url) {
		$paths = explode('/', $url);
		$domain = array_shift($paths);
		array_shift($paths);
		$r['m'] = array_shift($paths);
		$r['c'] = array_shift($paths);
		$r['a'] = array_shift($paths);
		$count = count($paths);
		for ($i = 0; $i < $count; $i++) {
			$_GET[$paths[$i]] = $paths[++$i];
		}
		return $r;
	}
	
	//get模式url处理
	protected function get_handler($url) {
		$paths = explode('&', $url);
		$r = array();
		foreach ($paths as $key => $value) {
			$t = explode('=', $value);
			$r[$t[0]] = $t[1];
		}
		return $r;
	}
}

?>